package com.fsl.springbootio.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO复制文件
 */
public class NIOCopyFile {

    public static void nioCopyFile(String resource,String destination) throws Exception{

        //获取文件的输入流
        FileInputStream fis = new FileInputStream(resource);
        //获取文件的输出流
        FileOutputStream fos = new FileOutputStream(destination);
        //读文件通道
        FileChannel readChannel = fis.getChannel();
        //写文件通道
        FileChannel writeChannel = fos.getChannel();
        //数据缓存
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while(true){
            //clear()为读写数据做准备
            byteBuffer.clear();
            int len = readChannel.read(byteBuffer);//读入数据
            if(len == -1){
                break;
            }
            byteBuffer.flip();
            writeChannel.write(byteBuffer);//写入数据
        }
        readChannel.close();
        writeChannel.close();
    }
}
